<template>
  <el-dialog
    v-model:model-value="isShowDialog"
    :title="mode === 'edit' ? '编辑会员任务' : '新增会员任务'"
    :close-on-click-modal="false"
    width="650px"
    append-to-body
    destroy-on-close
    @open="handleOpened"
    @close="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="formRules"
    >
      <el-form-item
        v-if="props.mode === 'create'"
        class="common-form-width"
        label="选择任务"
        prop="taskId"
      >
        <el-cascader
          v-model="taskCascaderModel"
          clearable
          filterable
          :debounce="700"
          :props="taskCascaderProps"
          @change="handleTaskCascaderChange"
        />
      </el-form-item>
      <el-form-item
        class="common-form-width"
        label="任务名称"
        prop="name"
      >
        <el-input
          v-model="form.name"
          placeholder="请输入任务名称"
        />
      </el-form-item>
      <el-form-item
        class="common-form-width"
        label="任务描述"
        prop="description"
      >
        <el-input
          v-model="form.description"
          placeholder="请输入任务描述"
        />
      </el-form-item>
      <el-form-item
        label="任务图片"
        prop="img"
      >
        <upload
          v-model:model-value="form.img"
          list-type="picture-card"
          :limit="1"
          @success="handleImgUploadSuccess"
        >
          <el-icon>
            <Plus />
          </el-icon>
        </upload>
      </el-form-item>
      <el-form-item
        label="限制条件"
        prop="limit"
      >
        <div class="item-block item-block__prefix">
          每人
        </div>
        <div class="item-block">
          <el-select v-model="form.granularity">
            <el-option
              v-for="item in unitOptions"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div class="item-block  item-block__prefix">
          领取
        </div>
        <div class="item-block">
          <el-input v-model="form.count">
            <template #append>
              次
            </template>
          </el-input>
        </div>
      </el-form-item>

      <el-form-item
        label="任务奖励"
        prop="award"
      >
        <div class="award-form-item">
          <el-row
            :gutter="10"
            style="margin-bottom: 10px"
          >
            <el-col :span="4">
              <el-checkbox
                v-model="currencyCheckBoxModel"
                label="代币奖励"
              />
            </el-col>
            <el-col :span="10">
              <el-select
                v-model="form.payOfCurrencyId"
                placeholder="选择代币单位"
                @change="handlePayOfCurrencyIdChange"
              >
                <el-option
                  v-for="item in currencyOptions"
                  :value="item.id"
                  :label="item.name"
                />
              </el-select>
            </el-col>
            <el-col :span="10">
              <el-input
                v-model="form.payOfCurrencyCount"
                placeholder="输入数量"
              />
            </el-col>
          </el-row>

          <el-row
            :gutter="10"
            style="margin-bottom: 10px"
          >
            <el-col :span="4">
              <el-checkbox
                v-model="benefitCheckBoxModel"
                label="权益奖励"
              />
            </el-col>
            <el-col :span="10">
              <el-paged-select
                v-model:model-value="form.goodsId"
                url="merchant/member/goods/pageProduct"
                search-key="productName"
                :params="{withProducts: true}"
                option-key="id"
                placeholder="选择权益"
                @change="handleGoodsIdChange"
              >
                <template #default="{optionData}">
                  <el-option
                    :label="optionData.name"
                    :value="optionData.id"
                  />
                </template>
              </el-paged-select>
            </el-col>
            <el-col :span="10">
              <el-select
                v-model="form.productId"
                placeholder="选择规格"
              >
                <el-option
                  v-for="item in productsOptions"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-col>
          </el-row>

          <el-row
            :gutter="10"
            style="margin-bottom: 10px"
          >
            <el-col :span="4">
              <el-checkbox
                v-model="growthCheckBoxModel"
                label="成长值"
              />
            </el-col>
            <el-col :span="10">
              <el-input
                v-model.number="form.growth"
                type="number"
                placeholder="请输入成长值"
              />
            </el-col>
            <el-col :span="10">
              <el-select
                v-model="form.growthExpireType"
                placeholder="请选择有效期"
              >
                <el-option
                  :value="1"
                  label="会员到期失效"
                />
                <el-option
                  :value="2"
                  label="周末"
                />
                <el-option
                  :value="3"
                  label="月末"
                />
                <el-option
                  :value="4"
                  label="年末"
                />
                <el-option
                  :value="5"
                  label="永久有效"
                />
                <el-option
                  :value="6"
                  label="自定义"
                />
              </el-select>
            </el-col>
          </el-row>

          <el-row
            v-if="form.growthExpireType === 6"
            :gutter="10"
          >
            <el-col :span="4" />
            <el-col :span="10" />
            <el-col :span="10">
              <el-input
                v-model.number="form.growthExpireDays"
                :min="1"
              >
                <template #append>
                  天失效
                </template>
              </el-input>
            </el-col>
          </el-row>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleCancel">
        取消
      </el-button>
      <el-button
        type="primary"
        @click="handleConfirm"
      >
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {addVipRank, changeTask, editVipRank} from "@/api/vipCenter";
import {IRankItem, IRankTaskEditData, IRankTaskItem} from "@/api/modules/vipCenter";
import {getTaskCategory, getTaskInfoList} from "@/api/taskCenter";
import {FormRules} from "element-plus";
import {frequency} from "@/views/vipCenter/dict/frequency";
import {getCurrencysApi} from "@/api/activity";
import {getCurrencyTypes} from "@/api/pointsMall";
import {ICurrencyItem} from "@/api/modules/pointsMall";
import {positiveInteger_0} from "@/utils/commonRegexp";
import {ITaskCategoryItem, ITaskInfoItem} from "@/api/modules/taskCenter";
import {UnwrapRef} from "vue";

const props = defineProps<{
  show: boolean,
  mode: 'edit' | 'create',
  rowData: IRankTaskItem,
  selectedRank: IRankItem,
}>()
const emits = defineEmits(['update:show', 'confirm'])
const isShowDialog = computed({
  set(newValue) {
    emits('update:show', newValue)
  },
  get() {
    return props.show
  }
})

const formRef = ref()
const initForm = () => {
  return {
    memberId: null,
    taskId: null,
    name: '',
    description: '',
    img: '',
    granularity: null,
    count: null,
    payOfCurrencyId: null,
    payOfCurrencyCount: null,
    goodsId: null,
    productId: null,
    growth: null,
    growthExpireType: null,
    growthExpireDays: null,
  }
}
const form:UnwrapRef<IRankTaskEditData> = reactive(initForm())
const formRules = ref<FormRules>({
  taskId: [{required: true, message: '请选择任务配置', trigger: 'change'}],
  name: [{required: true, message: '请输入任务名称', trigger: 'blur'}],
  description: [{required: true, message: '请输入任务描述', trigger: 'blur'}],
  img: [{required: true, message: '请选择任务图片'}],
  limit: [{
    required: true, validator(rule, value, callback) {
      if (!form.granularity) {
        callback('请选择限制频率')
        return
      }

      if (!positiveInteger_0.test(''+form.count)) {
        callback('领取次数需为0或正整数')
        return
      }

      callback()
    }
  }],
  award: [{
    required: true, validator(rule, value, callback) {
      if (!currencyCheckBoxModel.value && !benefitCheckBoxModel.value && !growthCheckBoxModel.value) {
        callback('请选择或填写任一任务奖励')
        return
      }

      if (currencyCheckBoxModel.value) {
        if (!form.payOfCurrencyId) {
          callback('请选择代币单位')
          return
        }

        if (!positiveInteger_0.test(''+form.payOfCurrencyCount)) {
          callback('代币数量需为0或正整数')
          return
        }
      }

      if (benefitCheckBoxModel.value) {
        if (!form.goodsId) {
          callback('请选择权益')
          return
        }
      }
      callback()
    }
  }]
})

const isEmpty = (val:any) => {
  return val === '' || val === undefined || val === null
}

// 选择任务
const taskCascaderModel = ref()
const currentTaskCategories = ref<ITaskCategoryItem[]>([])
const currentTaskInfoList = ref<ITaskInfoItem[]>([])
const taskCascaderProps = {
  lazy: true,
  async lazyLoad(node: any, resolve: any) {
    const {level} = node
    if (level === 0) {
      const rs = await getTaskCategory({status: 1})
      if (rs.code === 200) {
        currentTaskCategories.value = rs.payload ?? []
        const nodes = rs.payload?.map(item => ({
          label: item.categoryName,
          value: item.id,
          leaf: false
        }))

        resolve(nodes)
      }
    } else {
      const rs = await getTaskInfoList({status: 1, categoryId: node.pathValues[node.pathValues.length - 1]})
      currentTaskInfoList.value = rs.payload ?? []
      if (rs.code === 200) {
        const nodes = rs.payload?.map(item => ({
          label: item.taskName,
          value: item.id,
          leaf: true,
        }))

        resolve(nodes)
      }
    }
  },
}
const handleTaskCascaderChange = (value: number[]) => {
  if (!value) {
    form.taskId = null
  } else {
    form.taskId = taskCascaderModel.value[taskCascaderModel.value.length - 1]
    const target = currentTaskInfoList.value.find(item => item.id === form.taskId)!
    fillFormByTaskItem(target)
  }
}
const fillFormByTaskItem = (taskInfo:ITaskInfoItem) => {
  Object.keys(taskInfo).forEach(key => {
    form[key] = taskInfo[key]
  })
  form.name = taskInfo.taskName
  form.description = taskInfo.taskDescription
  form.img = taskInfo.taskImg
}

// const handleTaskBeforeFilter = (value) => {
//   console.log('beforeFilter', value)
//
//   return true
// }
//
// const handleTaskFilter = (node: any, keyword: string) => {
//   console.log('node keyword', node, keyword)
//
//   return false
// }

// 任务图片
const handleImgUploadSuccess = ({name, url}: { name: string, url: string }) => {
  form.img = url
}

// 限制条件-任务频率
const unitOptions = ref(frequency)

// 任务奖励 代币奖励
const currencyCheckBoxModel = ref()
watch(currencyCheckBoxModel, (newValue) => {
  // 若取消勾选 清空form中相关的内容
  if (!newValue) {
    form.payOfCurrencyId = null
    form.payOfCurrencyCount = null
  }
})
const handlePayOfCurrencyIdChange = () => {
  currencyCheckBoxModel.value = true
}

// 任务奖励 代币单位
const currencyOptions = ref<ICurrencyItem[]>([])
const getCurrencyOptions = async () => {
  const rs = await getCurrencyTypes()
  if (rs.code === 200) {
    currencyOptions.value = rs.payload ?? []
  }
}
// 任务奖励 权益奖励 选择权益
const benefitCheckBoxModel = ref()
watch(benefitCheckBoxModel, (newValue) => {
  if (!newValue) {
    form.goodsId = null
    form.productId = null
  }
})
// 任务奖励 权益奖励 规格
const productsOptions = ref([])
const handleGoodsIdChange = (id: number, options: any) => {
  const goodsItem = options.find((item: any) => item.id === id)
  if (goodsItem.type === 'pack') {
    productsOptions.value = goodsItem?.packProducts ?? []
  } else {
    productsOptions.value = goodsItem?.products ?? []
  }
  form.productId = null
  benefitCheckBoxModel.value = true
}

// 任务奖励 成长值
const growthCheckBoxModel = ref()
watch(growthCheckBoxModel, (newValue) => {
  if (!newValue) {
    form.growth = null
    form.growthExpireDays = null
    form.growthExpireType = null
  }
})
watch([() => form.growth, () => form.growthExpireType, () => form.growthExpireDays], ([growth, growthExpireType, growthExpireDays]) => {
  if (!isEmpty(growth) || !isEmpty(growthExpireType) || !isEmpty(growthExpireDays)) {
    growthCheckBoxModel.value = true
  }
})

const handleOpened = () => {
  const initialForm = initForm()
  const formKeys = Object.keys(initialForm)
  formKeys.forEach(key => {
    form[key] = initialForm[key]
  });

  taskCascaderModel.value = false;
  currencyCheckBoxModel.value = false;
  benefitCheckBoxModel.value = false;
  growthCheckBoxModel.value = false;

  nextTick(() => {
    getCurrencyOptions()

    if (props.mode === 'edit') {
      Object.keys(props.rowData).forEach((key) => {
        form[key] = props.rowData[key]
      })

      if (form.payOfCurrencyId) {
        currencyCheckBoxModel.value = true
      }
      if (form.goodsId || form.productId) {
        benefitCheckBoxModel.value = true
      }
      if (form.growthExpireType) {
        growthCheckBoxModel.value = true
      }
    }
  })
}

const handleConfirm = async () => {
  if (!props.selectedRank?.id) {
    ElMessage.error('请先从左侧会员等级列表选择会员等级以添加')
    return
  }
  form.memberId = props.selectedRank.id
  if (props.mode === 'create') {
    form.id = null
  }
  const rs = await changeTask(form)

  if (rs.code === 200) {
    ElMessage.success('保存成功')
    isShowDialog.value = false
    emits('confirm')
  }
}

const handleCancel = () => {
  isShowDialog.value = false
}

const handleClosed = () => {
}
</script>

<style scoped lang="scss">
@use "@/components/goodsCenter/styles/common.scss";

.item-block {
  :deep(.el-select) {
    width: 200px;
  }

  :deep(.el-input) {
    width: 200px;
  }
}

.item-block:not(:first-child) {
  margin-left: 10px;
}

.item-block__prefix {
  width: 34px;
}

.award-form-item {
  display: flex;
  flex-direction: column;

  .award-line {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 10px;

    .checkbox {
      margin-right: 10px;
    }

    .content {
      display: flex;
    }
  }
}

:deep(.icon-arrow-down:before) {
  display: none;
}
</style>
